#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mpTcpSocket = new ZTcpSocket(this);
    connect(mpTcpSocket,SIGNAL(readyRead()),this,SLOT(slotReadyRead()));

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_Connect_clicked()
{
    if(ui->pushButton_Connect->text()==tr("连接"))
    {
        mpTcpSocket->connectServer();
        ui->pushButton_Connect->setText(tr("断开"));
    }
    else
    {
        mpTcpSocket->disconnectFromHost();
        ui->pushButton_Connect->setText(tr("连接"));
    }
}


void MainWindow::on_pushButton_Send_clicked()
{
    QString name = ui->lineEdit_Name->text();
    QString content = ui->textEdit_Send->toPlainText();
    QDateTime time = QDateTime::currentDateTime();
    ui->textEdit_Rec->setAlignment(Qt::AlignRight);
    mpTcpSocket->sendTcpData(name,content,time);
    ui->textEdit_Rec->setTextColor(Qt::green);
    ui->textEdit_Rec->setFontPointSize(9);


    ui->textEdit_Rec->append(tr("昵称:")+name+tr(" 时间:")+time.toString("yyyy-MM-dd hh:mm:ss")+"\n");
    ui->textEdit_Rec->setTextColor(Qt::blue);

    ui->textEdit_Rec->setFontPointSize(20);
    ui->textEdit_Rec->append(content+"\n");
}

void MainWindow::slotReadyRead()
{
    ZTcpSocket *tcpSocket = static_cast<ZTcpSocket *>(this->sender());
    ui->textEdit_Rec->setAlignment(Qt::AlignLeft);
    ui->textEdit_Rec->setTextColor(Qt::red);
    ui->textEdit_Rec->setFontPointSize(9);

    ZTcpData data = tcpSocket->readAllData();
    ui->textEdit_Rec->append(tr("昵称:")+data.Name()+tr(" 时间:")+data.Time().toString("yyyy-MM-dd hh:mm:ss")+"\n");
    ui->textEdit_Rec->setTextColor(Qt::blue);

    ui->textEdit_Rec->setFontPointSize(20);
    ui->textEdit_Rec->append(data.Content()+"\n");
}

